package com.azxcrm.project.system.wap.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.azxcrm.common.utils.DateUtils;
import com.azxcrm.common.utils.StringUtils;
import com.azxcrm.common.utils.security.ShiroUtils;
import com.azxcrm.framework.aspectj.lang.annotation.Log;
import com.azxcrm.framework.redis.template.service.RedisServiceImpl;
import com.azxcrm.framework.web.domain.Message;
import com.azxcrm.project.monitor.workflow.common.CommonService;
import com.azxcrm.project.monitor.workflow.domain.WorkFlowApply;
import com.azxcrm.project.monitor.workflow.service.WorkFlowApplyService;
import com.azxcrm.project.system.basic.domain.CustomerClueCommunication;
import com.azxcrm.project.system.basic.domain.OrderDispatch;
import com.azxcrm.project.system.basic.domain.OrderModifyRecord;
import com.azxcrm.project.system.basic.service.ICustomerClueCommunicationService;
import com.azxcrm.project.system.basic.service.IOrderDispatchService;
import com.azxcrm.project.system.basic.service.IOrderModifyRecordService;
import com.azxcrm.project.system.customer.domain.CustomerAttendance;
import com.azxcrm.project.system.customer.domain.CustomerClue;
import com.azxcrm.project.system.customer.service.ICustomerAttendanceService;
import com.azxcrm.project.system.customer.service.ICustomerClueService;
import com.azxcrm.project.system.dict.domain.DictData;
import com.azxcrm.project.system.dict.service.IDictDataService;
import com.azxcrm.project.system.order.domain.Order;
import com.azxcrm.project.system.order.domain.OrderVisitRecord;
import com.azxcrm.project.system.order.service.IOrderService;
import com.azxcrm.project.system.order.service.IOrderVisitRecordService;
import com.azxcrm.project.system.product.domain.ProductInfo;
import com.azxcrm.project.system.product.domain.ProductSpecification;
import com.azxcrm.project.system.product.service.IProductInfoService;
import com.azxcrm.project.system.product.service.IProductSpecificationService;
import com.azxcrm.project.system.user.domain.User;
import com.azxcrm.project.system.user.service.IUserService;

/**
 * @author YanLiang
 *
 */
@Controller
@RequestMapping("/wap")
public class OrderWapController {
	
	 private String prefix = "wap";

	
	@Autowired
	private IOrderService orderService;
	
	@Autowired
	private CommonService commonService;
	
	@Autowired
	private WorkFlowApplyService workFlowApplyService;
	
	/**
	 * 订单操作记录
	 */
	@Autowired
	private IOrderModifyRecordService orderModifyRecordService;
	
	/**
	 * 常见问题类型
	 */
	@Autowired
	private IDictDataService dictDataService;
	
	/**
	 * 回访记录表
	 */
	@Autowired
	private IOrderVisitRecordService orderVisitRecordService;

	/**
	 * 客户线索
	 */
	@Autowired
	private ICustomerClueService customerClueService;

	/**
	 * 参课信息
	 */
	@Autowired
	private ICustomerAttendanceService customerAttendanceService;
	
	/**
	 * 客服沟通记录
	 */
	@Autowired
	private ICustomerClueCommunicationService customerClueCommunicationService;
	
	/**
	 * 派单记录
	 */
	@Autowired
	private IOrderDispatchService orderDispatchService;
	
	/**
	 * 用户信息
	 */
	@Autowired
	private IUserService userService;
	
	/**
	 * 产品
	 */
	@Autowired
	private IProductSpecificationService productSpecificationService;
	
	/**
	 * 产品类型
	 */
	@Autowired
	private IProductInfoService productInfoService;
	
	/**
	 * Redis服务
	 */
	@Autowired
	private RedisServiceImpl redisServiceImpl;
	
	@Autowired
	private RuntimeService runtimeService;
	
	/**
	 * 派单员角色
	 */
	@Value("${crm.role.dispatcher}")
	private String dispatcher;

	/**
	 * 派单员主管
	 */
	@Value("${crm.role.dispatcherManager}")
	private String dispatcherManager;

	/**
	 * 字典产品类型
	 */
	@Value("${crm.dictionary.product.type.orign}")
	private String productType;
	
	/**
	 * 拜访类型
	 */
	@Value("${crm.dictionary.visit.type}")
	private String visitType;
	
	/**
	 * 部门经理角色Key
	 */
	@Value("${crm.role.departmentManager}")
	private String departmentManager;

	/**
	 * 业务员角色
	 */
	@Value("${crm.role.salesman}")
	private String salesman;
	/**
	 * 待分配订单
	 * @param model
	 * @return
	 * @throws ParseException 
	 */
	@Log(title = "工作台", action = "wap端待分配订单")
	@GetMapping("/wapFollowOrder")
	public String wapFollowOrder(@RequestParam("userId")Integer userId, Model model) throws ParseException {
		Order order = new Order();
		User user = userService.selectUserById(userId.longValue());
		order.setOrderStatus(1);
		order.setDeptId(user.getDeptId().intValue());
		List<Order> orderList= orderService.selectOrderList(order);
		model.addAttribute("orderList", orderList);

		if(ShiroUtils.hasRole(dispatcherManager)) {
			orderList = orderService.selectOrderList(order);
			return prefix + "/order/orderFollow";
		}else if(ShiroUtils.hasRole(dispatcher)){
			order.setDeptId(ShiroUtils.getUser().getDeptId().intValue());
			orderList = orderService.selectOrderList(order);
			return prefix + "/order/orderFollow";
		}
		return prefix + "/order/orderFollow";
	}
	
	/**
	 * 待分配订单详情
	 * @param model
	 * @return
	 * @throws ParseException 
	 */
	@Log(title = "工作台", action = "wap端待分配订单详情")
	@GetMapping("/wapOrderFollowDetails")
	public String wapOrderFollowDetails(@RequestParam("orderId")Integer orderId,Model model) throws ParseException {
		// 查询订单信息
		Order order = orderService.selectOrderById(orderId);
		model.addAttribute("orderList", order);
		
		// 查询待跟进订单信息
		CustomerClue customerClue = customerClueService.selectCustomerClueById(order.getClueId());
		model.addAttribute("customerClue", customerClue);
		
		// 参课记录
		List<CustomerAttendance> customerAttendance = customerAttendanceService
				.selectCustomerAttendanceByCellphone(customerClue.getCustomerCellphone());
		model.addAttribute("customerAttendanceList", customerAttendance);
		
		//获取客服电话
		User user = userService.selectUserById(order.getServiceUserId().longValue());
		model.addAttribute("user", user);				
		
		// 查询客服沟通记录
		CustomerClueCommunication clueCommunication = customerClueCommunicationService
				.selectCustomerClueCommunicationByClueId(order.getClueId());
		model.addAttribute("clueCommunication", clueCommunication);

		return prefix + "/order/orderFollowDetails";
	}
	
	

	/**
	 * 选择销售人员
	 * @param model
	 * @return
	 */
	@Log(title = "工作台", action = "wap端选择销售人员派单")
	@GetMapping("/wapSelectSales")
	public String wapSelectSales(@RequestParam("orderId")Integer orderId,Model model) {

		// 派单业务员
		Order order =orderService.selectOrderById(orderId);
		List<User> users = userService.selectUserByOrder(order.getOrderId(),order.getDeptId(),salesman);
		model.addAttribute("users", users);
		model.addAttribute("orderId", orderId);
		return prefix + "/order/selectSales";
	}
	
	/**
	 * 提交选择业务员
	 * @param orderId
	 * @param model
	 * @return
	 * @throws ParseException
	 */
	@Log(title = "工作台", action = "wap端提交选择业务员")
	@PostMapping("/wapSelectSalesSave")
	@ResponseBody
	public Message wapSelectSalesSave(Order odr,Model model) throws ParseException {
		
		Order order = orderService.selectOrderById(odr.getOrderId());
		order.setSalesUserId(odr.getSalesUserId());
		// 订单表状态修改
		User user = userService.selectUserById(order.getSalesUserId().longValue());
		order.setSalesUserId(user.getUserId().intValue());
		order.setSalesUserName(user.getLoginName());
		order.setOrderStatus(2);
		Order or = orderService.selectOrderById(order.getOrderId());	

		// 修改派单记录
		OrderDispatch orderDispatch = new OrderDispatch();
		orderDispatch.setOrderId(order.getOrderId());
		orderDispatch.setDispatchStatus(0);
		OrderDispatch dispatch = orderDispatchService.selectOrderDispatchByDispatch(orderDispatch);
		orderDispatch.setDispatchId(dispatch.getDispatchId());//设置派单id
		orderDispatch.setDispatchStatus(1);//设置派单状态
		orderDispatch.setSalesUserId(order.getSalesUserId());//设置业务员ID
		CustomerAttendance customerAttendance = new CustomerAttendance();
		// 客户线索查询
		CustomerClue customerClue = customerClueService.selectCustomerClueById(or.getClueId());
		customerAttendance.setCellphoneNum(customerClue.getCustomerCellphone());
		customerAttendance.setSalesUserId(order.getSalesUserId());
		CustomerAttendance dance = customerAttendanceService.selectCustomerAttendanceNewest(customerAttendance);
		String currentDate = DateUtils.plusDay(30,DateUtils.getDate());//当前时间+30天
		//判断有没有参课记录
		if(null == dance) {
			orderDispatch.setProtectType(0);//设置为参课保护类型
			orderDispatch.setProtectTime(currentDate);//参课保护时间，当前时间+30天
		}else {
			String danceDate = DateUtils.plusDay(30,dance.getAttendanceTime());//跟单保护时间，参课时间+30天
			//有参课记录但是参课时间+30天小于当前时间
			if(DateUtils.compare_date(DateUtils.getDate(), danceDate)) {
				orderDispatch.setProtectType(1);//设置为更单保护类型
				orderDispatch.setProtectTime(currentDate);//跟单保护时间，参课时间+30天
			}else {
				orderDispatch.setProtectType(1);//设置为更单保护类型
				orderDispatch.setProtectTime(danceDate);//跟单保护时间，参课时间+30天
			}
		}

		// 新增订单操作记录
		OrderModifyRecord orderModifyRecord = new OrderModifyRecord();
		orderModifyRecord.setOrderId(order.getOrderId());
		orderModifyRecord.setModifyUserId(ShiroUtils.getUserId().intValue());
		orderModifyRecord.setModifyType(3);
		orderModifyRecord.setModifyRecod("业务员派单");

		if (orderService.updateOrder(order) > 0 && orderDispatchService.updateOrderDispatch(orderDispatch) > 0
				&& orderModifyRecordService.saveOrderModifyRecord(orderModifyRecord) > 0) {
			return Message.ok();
		}
		return Message.error();
	}
	
	/**
	 * 待跟进订单保护期内订单详情
	 * @param model
	 * @return
	 * @throws ParseException 
	 */
	@Log(title = "工作台", action = "wap端待跟进订单保护期内")
	@GetMapping("/wapOrderDetail")
	public String wapOrderDetails(@RequestParam("orderId")Integer orderId,@RequestParam("status")Integer status,
				Model model) throws ParseException{
		
		// 查询订单信息
		Order order= orderService.selectOrderById(orderId);
		model.addAttribute("order", order);

		// 查询客户线索信息
		CustomerClue customerClue = customerClueService.selectCustomerClueById(order.getClueId());
		model.addAttribute("customerClue", customerClue);
		
		// 参课记录
		List<CustomerAttendance> customerAttendance = customerAttendanceService
				.selectCustomerAttendanceByCellphone(customerClue.getCustomerCellphone());
		model.addAttribute("customerAttendanceList", customerAttendance);
		
		//获取客服电话
		User user = userService.selectUserById(order.getServiceUserId().longValue());
		model.addAttribute("user", user);		
		
		//查询剩余保有时间
		OrderDispatch orDispatch = new OrderDispatch();
		orDispatch.setSalesUserId(order.getSalesUserId());
		orDispatch.setOrderId(orderId);
		OrderDispatch orderDispatch = orderDispatchService.selectOrderDispatchByDispatch(orDispatch);
		model.addAttribute("orderDispatch", orderDispatch);
		long protectDay = DateUtils.getDaySub(DateUtils.getDate(), orderDispatch.getProtectTime());
		model.addAttribute("protectDay", protectDay);
		
		// 查询客服沟通记录
		CustomerClueCommunication clueCommunication = customerClueCommunicationService
				.selectCustomerClueCommunicationByClueId(order.getClueId());
		model.addAttribute("clueCommunication", clueCommunication);
		
		//查询跟单记录
		List<OrderVisitRecord> orderVisitRecords= orderVisitRecordService.selectOrderVisitRecordByOrderId(orderId);
		model.addAttribute("orderVisitRecords", orderVisitRecords);
		model.addAttribute("status", status);
		
		return prefix + "/order/orderDetail";
	}
	
	/**
	 * 查询已过保护期订单
	 * @param model
	 * @return
	 */
	@Log(title = "工作台", action = "wap端已过保护期订单")
	@GetMapping("/wapOrderReason")
	public String wapOrderReason(@RequestParam("orderId")Integer orderId,@RequestParam("status")Integer status,@RequestParam("dispatchId")Integer dispatchId,Model model) {
		Order order = orderService.selectOrderById(orderId);
		model.addAttribute("dispatchId", dispatchId);
		model.addAttribute("status", status);
		model.addAttribute("order",order);
		return prefix + "/order/orderReason";
	}
	
	/**
	 * 待跟进订单列表
	 * @param order
	 * @param model
	 * @return
	 * @throws ParseException
	 */
	@Log(title = "工作台", action = "wap端待跟进订单列表")
	@GetMapping("/wapOrderFollowDetail")
	public String wapOrderFollowDetail(Order order,Model model) throws ParseException {
    
       //获取待跟进订单信息
  		OrderDispatch orderDispatch = new OrderDispatch();
  		order.setSalesUserId(ShiroUtils.getUserId().intValue());
  		orderDispatch.setOrder(order);
		
  		//查询跟进中列表信息
  		List<OrderDispatch> dispatchList = orderDispatchService.wapOrderDispatchList(orderDispatch);
  		List<OrderDispatch> orderDispatchList = new ArrayList<OrderDispatch>();
  		for (OrderDispatch od : dispatchList) {
  			Long dateNum = DateUtils.getDaySub(DateUtils.getDate(), od.getProtectTime());
  			od.setDateNum(dateNum);
  			orderDispatchList.add(od);
  			if(dateNum<0) {
  				order.setOrderStatus(0);
  				}
  		}
  		model.addAttribute("orderDispatchList", orderDispatchList);
 	     
		return prefix + "/order/orderFollowDetail";
	}
	/**
	 * 提交未成单原因
	 * @param orderId
	 * @param orderDispatch
	 * @return
	 */
	@Log(title = "工作台", action = "wap端提交未成单原因")
	@PostMapping("/wapOrderReasonSave")
	@ResponseBody
	public Message wapOrderReasonSave(@RequestParam("orderId")Integer orderId,OrderDispatch orderDispatch) {
		OrderDispatch dispatch = orderDispatchService.selectOrderDispatchById(orderDispatch.getDispatchId());
		dispatch.setUnformedCause(orderDispatch.getUnformedCause());
		if (orderDispatchService.saveOrderDispatch(dispatch) > 0) {
			return Message.ok();
		}
		return Message.error();
	}
	
	/**
	 * 查询跟单记录详情
	 * @param model
	 * @return
	 */
	@Log(title = "工作台", action = "wap端查询跟单记录详情")
	@GetMapping("/wapOrderFollowRecordDetails")
	public String orderFollowRecordDetails(@RequestParam("recordId")Integer recordId,Model model) {
		 OrderVisitRecord orderVisitRecord= orderVisitRecordService.selectOrderVisitRecordById(recordId);
		 model.addAttribute("orderVisitRecord", orderVisitRecord);
		return prefix + "/order/orderFollowRecordDetails";
	}
	
	/**
	 * AJAX获取拜访类型
	 * @param model
	 * @return
	 */
	@Log(title = "工作台", action = "wap端获取拜访类型")
	@GetMapping("/getVisit")
	@ResponseBody
	public List<DictData> getVisit(Model model) {
		List<DictData> visitList = dictDataService.selectDictDataByDictType(visitType);
		return visitList;
	}
	
	/**
	 * 新增跟单记录
	 * @param model
	 * @return
	 */
	@Log(title = "工作台", action = "wap端新增跟单记录")
	@GetMapping("/wapOrderFollowAdd")
	public String wapOrderFollowAdd(@RequestParam("orderId")Integer orderId,@RequestParam("status")Integer status,
			Model model) {
		// 查询订单信息.
		Order order = orderService.selectOrderById(orderId);
		model.addAttribute("order", order);
		
		List<DictData> visitList = dictDataService.selectDictDataByDictType(visitType);
		model.addAttribute("visitList", visitList);
		model.addAttribute("status", status);
		
		return prefix + "/order/orderFollowAdd";
	}
	
	/**
	 * 添加拜访记录
	 * @param orderVisitRecord
	 * @return
	 */
	@Log(title = "工作台", action = "wap端添加拜访记录")
	@PostMapping("/saveRecord")
	@ResponseBody
	public Message saveRecord(OrderVisitRecord orderVisitRecord) {	
		Order order = orderService.selectOrderById(orderVisitRecord.getOrderId());
		orderVisitRecord.setOrderNum(order.getOrderNum());
		orderVisitRecord.setTypeId(order.getTypeId());
		orderVisitRecord.setServiceUserId(order.getServiceUserId());
		orderVisitRecord.setSalesUserId(order.getSalesUserId());
		orderVisitRecord.setVisitStatus(0);
		orderVisitRecord.setCreateBy(order.getSalesUserName());
		if (orderVisitRecordService.saveOrderVisitRecord(orderVisitRecord)>0) {
			return Message.ok();
		}
		return Message.error();
	}
	
	/**
	 * 完善订单记录
	 * @param model
	 * @return
	 */
	@Log(title = "工作台", action = "wap端完善订单记录")
	@GetMapping("/wapOrderPerfect")
	public String wapOrderPerfect(@RequestParam("orderId")Integer orderId,@RequestParam("status")Integer status,Model model) {
		// 查询订单信息.
		Order order = orderService.selectOrderById(orderId);
		model.addAttribute("order", order);
		
		// 产品类型
		List<DictData> productTypeList = dictDataService.selectDictDataByDictType(productType);
		model.addAttribute("productTypeList", productTypeList);
		model.addAttribute("status", status);
		
		return prefix + "/order/orderPerfect";
	}
	
	/**
	 * AjAX获取订单类型
	 * @return
	 */
	@Log(title = "工作台", action = "wap端获取订单类型")
	@GetMapping("/getOrderType")
	@ResponseBody
	public List<DictData> getOrderType() {
		//订单类型类型
		List<DictData> productList = dictDataService.selectDictDataByDictType(productType);
		return productList;
	}
	
	/**
	 * AjAX获取产品品种
	 * @param productSpecification
	 * @return
	 */
	@Log(title = "工作台", action = "wap端获取产品品种")
	@GetMapping("/getProductSpecification")
	@ResponseBody
	public List<ProductSpecification> getProductSpecification(ProductSpecification productSpecification) {
		//商品类型
		List<ProductSpecification> specification = productSpecificationService.selectProductSpecificationList(productSpecification);
		return specification;
	}
	
	/**
	 * AjAX获取产品类型
	 * @param productInfo
	 * @return
	 */
	@Log(title = "工作台", action = "wap端获取产品类型")
	@GetMapping("/getProductInfo")
	@ResponseBody
	public List<ProductInfo> getProductInfo(ProductInfo productInfo) {
		//商品类型
		List<ProductInfo> specification = productInfoService.selectProductInfoList(productInfo);
		return specification;
	}
	
	
	/**
	 * 订单提交审核
	 * @param model
	 * @return
	 */
	@Log(title = "工作台", action = "wap端订单提交审核")
	@PostMapping("/saveOrder")
	@ResponseBody
	public Message saveOrder(Order order) {
		try {
			//结单时开启成单审批工作流
			String businessId = UUID.randomUUID().toString();
			//flowId 1:成单审批 2：退单审批
			WorkFlowApply workFlowApply = new WorkFlowApply(ShiroUtils.getUserId().intValue(), businessId, 1, "成单审批", order.getOrderId());
			
			if (workFlowApplyService.saveWorkFlowApply(workFlowApply) > 0) {
				// 只有在新增情况下才能开启流程
				if (StringUtils.isNull(workFlowApply.getApplyId())) {
					//开启成单审批流程
					commonService.startProcess(businessId,workFlowApply);
					
					//修改订单状态
					Order orderInfo = new Order(order.getOrderId(), 3, 1, 1);
					orderService.updateOrder(orderInfo);
					orderService.updateOrder(order);
					
					//新增订单修改记录
					OrderModifyRecord orderModifyRecord = new OrderModifyRecord(order.getOrderId(), ShiroUtils.getUserId().intValue(), 3, "发起结单");
					orderModifyRecordService.insertOrderModifyRecord(orderModifyRecord);
				
					return Message.ok();
				}

			}
			
		} catch (Exception e) {
			return Message.error();
		}
		return Message.error();
	}
	
	/**
	 * 待审核订单列表
	 * @param model
	 * @return
	 */
	@Log(title = "工作台", action = "wap端待审核订单列表")
	@GetMapping("/examineList")
	public String examineList(Model model) {
		Order order = new Order();
		//待审批事项
   		if(ShiroUtils.hasRole(departmentManager)) {
   			List<Order> orders = new ArrayList<>();
   			ArrayList<String> businessKeys = new ArrayList<>();
   			String businessKey = "";
   			List<Task> list = commonService.findTaskByUserId(String.valueOf(ShiroUtils.getUserId()));
   			for (Task task : list) {
   				ProcessInstance result = runtimeService.createProcessInstanceQuery()
   						.processInstanceId(task.getProcessInstanceId()).singleResult();
   				// 获得业务流程的bussinessKey
   				businessKey = result.getBusinessKey();
   				businessKeys.add(businessKey);
   				WorkFlowApply flowInfo = workFlowApplyService.selectWorkFlowApplyByBusinessId(businessKey);
   				if (flowInfo.getOrderId() != null) {
					//将TaskId保存在Redis中:K-orderId:V-taskId
					redisServiceImpl.set(flowInfo.getOrderId().toString(), task.getId());
					redisServiceImpl.expire(flowInfo.getOrderId().toString(), 60); //设置缓存过期时间
				}
   			}
   			//查询订单IDs
			Integer[] orderIdListIds = workFlowApplyService.selectWorkFlowApplyByBusinessIds(businessKeys);
			order.setOrderIds(orderIdListIds);
			//查询订单信息
			order.setOrderType(1);
			order.setAuditType(2);
			order.setOrderStatus(3);
			order.setDeptId(ShiroUtils.getUser().getDeptId().intValue());
			orders = orderService.selectOrderAuditList(order);
			if(orders != null && orders.size()>0){
				for(Order orderInfo : orders){
					//将缓存中的taskId填充到订单数据中
					orderInfo.setTaskId(redisServiceImpl.get(orderInfo.getOrderId().toString()).toString());
				}
			}
   			model.addAttribute("examine", orders);
   		}else {
   			model.addAttribute("examine", 1);
   		}
		return prefix + "/order/examineList";
	}
	
	/**
	 * 退单审核详情
	 */
	@Log(title = "工作台", action = "wap端退单审核详情")
	@GetMapping("/approve")
	public String approve(@RequestParam("orderId")Integer orderId,@RequestParam("taskId") String taskId,Model model) {
		Order order = orderService.selectOrderById(orderId);
		model.addAttribute("order", order);
		model.addAttribute("taskId", taskId);
		return prefix + "/order/approve";
	}
	
	/**
	 * 退单审核提交
	 */
	@Log(title = "工作台", action = "wap端退单审核提交")
	@PostMapping("/saveApprove")
	@ResponseBody
	public Message saveApprove(@RequestParam("taskId") String taskId,@RequestParam("audit") String audit) {
		commonService.completeTaskByUser(taskId, String.valueOf(ShiroUtils.getUserId()), audit);
		return Message.ok();
	}
	
}
	